package edu.uclmgmu.bacteriosec.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;

import edu.uclmgmu.bacteriosec.domain.data.AspectFamily;
import edu.uclmgmu.bacteriosec.domain.data.CallResult;
import edu.uclmgmu.bacteriosec.domain.data.ListOfAspectsFamilies;
import edu.uclmgmu.bacteriosec.domain.data.MethodCatched;
import edu.uclmgmu.bacteriosec.domain.data.TestCaseExecuted;

public class JDExecutionResults extends JDialog {

	private final JPanel contentPanel = new JPanel();
	private JEditorPane editorPane;
	private String resultsPath;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			JDExecutionResults dialog = new JDExecutionResults();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public JDExecutionResults() {
		setBounds(100, 100, 704, 395);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new GridLayout(0, 1, 0, 0));
		{
			JScrollPane scrollPane = new JScrollPane();
			contentPanel.add(scrollPane);
			{
				editorPane = new JEditorPane();
				scrollPane.setViewportView(editorPane);
				editorPane.setContentType("text/plain");
			}
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						setVisible(false);
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				buttonPane.add(cancelButton);
			}
		}
	}

	public void loadResults(String resultsPath, ListOfAspectsFamilies loaf) {
		try {
			FileOutputStream fos=new FileOutputStream(this.resultsPath+"summary.html"); 
			fos.write("<h1>Execution results</h1>".getBytes());
			Enumeration<AspectFamily> families = loaf.getFamilies();
			while (families.hasMoreElements()) {
				AspectFamily af=families.nextElement();
				fos.write(("<h1>" + af.getName() + "</h1>").getBytes());
				Vector<CallResult> ccrr=af.getCallResults();
				Vector<String> aspectClassFiles=loadAspectClassFiles(ccrr);
				for (String aspectClassFile : aspectClassFiles) {
					Vector<TestCaseExecuted> ttcc=loadTestCases(ccrr, aspectClassFile);
					Vector<Integer> callNumbers=loadCallNumbers(ccrr, aspectClassFile);
					int filas=callNumbers.size()+1; int columnas=ttcc.size()+1;
					String[][] tabla=new String[filas][columnas];
					tabla[0][0]="Call";
					for (int col=1; col<columnas; col++) {
						tabla[0][col]=ttcc.get(col-1).getShortName();
					}
					for (int fila=1; fila<filas; fila++) {
						tabla[fila][0]=""+callNumbers.get(fila-1);
					}
					
					for (Integer callNumber : callNumbers) {
						Vector<CallResult> iiccrr=loadCallResults(ccrr, aspectClassFile, callNumber);
						for (CallResult icr : iiccrr) {
							coloca(tabla, icr);
						}
					}
					salva(fos, af, aspectClassFile, tabla);
				}
			}		
			fos.close();
			this.editorPane.setPage("file://" + this.resultsPath+"summary.html");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void salva(FileOutputStream fos, AspectFamily af, String aspectClassFile, String[][] tabla) throws IOException {
		String texto="<table border=\"1\"><tr><th colspan=\"" + (1 + tabla.length) + "\">" + af.getName() + "</th></tr>";
		texto+="<tr><th colspan=\"" + (1 + tabla.length) + "\">" + aspectClassFile + "</th></tr>";
		fos.write(texto.getBytes());
		fos.flush();
		texto="<tr>";
		for (int col=0; col<tabla[0].length; col++) {
			texto+="<th>" + tabla[0][col] + "</th>";
		}
		texto+="</tr>";
		fos.write(texto.getBytes());
		String result;
		for (int fila=1; fila<tabla.length; fila++) {
			texto="<tr><th>" + tabla[fila][0] + "</th>";
			for (int col=1; col<tabla[0].length; col++) {
				result=tabla[fila][col];
				if (result!=null) {
					if (result.equals("P"))
						texto+="<td align=\"center\" bgcolor=\"GREEN\">" + result + "</td>";
					else 
						texto+="<td align=\"center\" bgcolor=\"RED\">" + result + "</td>";
				} else {
					texto+="<td></td>";
				}
			}
			texto+="</tr>";
			fos.write(texto.getBytes());
		}
		texto="</table>";
		fos.write(texto.getBytes());
	}

	private void coloca(String[][] tabla, CallResult icr) {
		int columnaBuscada=-1;
		for (int col=1; col<tabla[0].length; col++) {
			if (tabla[0][col].equals(icr.getTestCase().getShortName())) {
				columnaBuscada=col;
				break;
			}
		}
		int filaBuscada=-1;
		for (int fila=1; fila<tabla.length; fila++) {
			if (Integer.parseInt(tabla[fila][0])==icr.getCallNumber()) {
				filaBuscada=fila;
				break;
			}
		}
		if (columnaBuscada!=-1 && filaBuscada!=-1) {
			tabla[filaBuscada][columnaBuscada]=icr.getResult();
		}
	}

	private Vector<TestCaseExecuted> loadTestCases(Vector<CallResult> ccrr, String aspectClassFile) {
		Vector<TestCaseExecuted> result=new Vector<TestCaseExecuted>();
		for (CallResult cr : ccrr) {
			if (cr.getAspectClassFile().equals(aspectClassFile) && !result.contains(cr.getTestCase()))
				result.add(cr.getTestCase());
		}
		return result;
	}

	private Vector<CallResult> loadCallResults(Vector<CallResult> ccrr, String aspectClassFile, Integer callNumber) {
		Vector<CallResult> result=new Vector<CallResult>();
		for (CallResult cr : ccrr) {
			if (cr.getAspectClassFile().equals(aspectClassFile) && cr.getCallNumber()==callNumber && !result.contains(cr))
				result.add(cr);
		}
		return result;
	}

	private Vector<Integer> loadCallNumbers(Vector<CallResult> ccrr, String aspectClassFile) {
		Vector<Integer> result=new Vector<Integer>();
		for (CallResult cr : ccrr) {
			if (cr.getAspectClassFile().equals(aspectClassFile) && !result.contains(cr.getCallNumber()))
				result.add(cr.getCallNumber());
		}
		return result;
	}

	private Vector<String> loadAspectClassFiles(Vector<CallResult> ccrr) {
		Vector<String> result=new Vector<String>();
		for (CallResult cr : ccrr) {
			if (!result.contains(cr.getAspectClassFile()))
				result.add(cr.getAspectClassFile());
		}
		return result;
	}

	private void buildCabecera(FileOutputStream fos, AspectFamily af, String aspectClassFile, Vector<TestCaseExecuted> ttcc) throws IOException {
		String texto="<table border=\"1\"><tr><th colspan=\"" + (1 + ttcc.size()) + "\">" + af.getName() + "</th></tr>";
		texto+="<tr><th colspan=\"" + (1 + ttcc.size()) + "\">" + aspectClassFile + "</th></tr>";
		texto+="<tr><th>Call</th>";
		for (TestCaseExecuted tc : ttcc) {
			texto+="<th>" + tc.getShortName() + "</th>";
		}
		texto+="</tr>";
		fos.write(texto.getBytes());
		fos.flush();
	}

/*	public void setResults(ListOfAspectsFamilies loaf) {
		try {
			FileOutputStream fos=new FileOutputStream(this.resultsPath+"summary.html");
			fos.write("<h1>Execution results</h1>".getBytes());
			
			Enumeration<AspectFamily> families = loaf.getFamilies();
			while (families.hasMoreElements()) {
				AspectFamily af=families.nextElement();
				Vector<String> tests=new Vector<String>();
				af.loadTestCaseNames(tests);
				String cabecera="<table border=\"1\">";
				cabecera+="<tr><th colspan=\"" + (tests.size() + 1) + "\">" + af.getName() + "</th></tr>";
				fos.write(cabecera.getBytes());
				
				Enumeration<MethodCatched> mmcc = af.getMethodsCatched(); 
				int filas=af.getNumberOfCalls();
				
				while (mmcc.hasMoreElements()) {
					MethodCatched mc=mmcc.nextElement();
					cabecera="<tr><th colspan=\"" + (tests.size() + 1) + "\">" + mc.getName() + "</th></tr>";
					fos.write(cabecera.getBytes());
					Vector<TestCaseExecuted> ttcc = mc.getTestCases();
					int columnas=ttcc.size();
					cabecera="<tr><th>" + "Call" + "</th>";
					fos.write(cabecera.getBytes());
					for (int j=0; j<ttcc.size(); j++) {
						TestCaseExecuted tce=ttcc.get(j);
						cabecera="<th>" + tce.getShortName() + "</th>";
						fos.write(cabecera.getBytes());
					}
					cabecera="</tr>";
					fos.write(cabecera.getBytes());
					
					int currentCall=0;
					String[][] tabla=new String[columnas][filas];
					for (int columna=0; columna<ttcc.size(); columna++) {
						TestCaseExecuted tce=ttcc.get(columna);
						for (int fila=0; fila<tce.getCallResults().size(); fila++) {
							tabla[columna][fila+currentCall]=tce.getCallResult(fila).getResult();
						}
						currentCall+=tce.getNumberOfCalls();
					}					
					
					for (int fila=0; fila<filas; fila++) {
						cabecera="<tr><th>" + (fila + 1) + "</th>";
						fos.write(cabecera.getBytes());
						for (int columna=0; columna<ttcc.size(); columna++) {
							if (tabla[columna][fila]==null)
								cabecera="<td bgcolor=\"GREY\"></td>";
							else  {
								cabecera="<td align=\"center\" bgcolor=";
								if (tabla[columna][fila].equals("P")) {
									cabecera+="\"GREEN\">";
								} else if (tabla[columna][fila].equals("E")) {
									cabecera+="\"RED\">";
								} else if (tabla[columna][fila].equals("F")) {
									cabecera+="\"RED\">";
								}
								cabecera+=tabla[columna][fila];
								cabecera+="</td>";
							}
							fos.write(cabecera.getBytes());
						}
						cabecera="</tr>";
						fos.write(cabecera.getBytes());
						fos.flush();
					}
				}
				cabecera="</table>";
				fos.write(cabecera.getBytes());
			}						
			fos.close();
			this.editorPane.setPage("file://" + this.resultsPath+"summary.html");
		} 
		catch (Exception e) {
			this.editorPane.setText("Cound not create the results file: " + e.toString());
		}
	}*/

	public void setTempPath(String resultsPath) {
		this.resultsPath=resultsPath;
	}


}
